package com.oocl.servlet;


import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.exception.MyException;
import com.oocl.pojo.Customer;
import com.oocl.service.CustomerService;
import com.oocl.service.impl.CustomerServiceFactory;
import com.oocl.service.impl.ServiceFactory;



public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String salary = request.getParameter("salary");
		String birth = request.getParameter("birth");
		String sex = request.getParameter("sex");
		String[] favcs = request.getParameterValues("favcs");
		//check
		
		
		double sal = Double.parseDouble(salary);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date birthday = null;
		try {
			 birthday = df.parse(birth);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		boolean se = Boolean.parseBoolean(sex);
		int[] favcIds = new int[favcs.length];
		for(int i=0;i<favcs.length;i++){
			favcIds[i] = Integer.parseInt(favcs[i]);
		}
		
	    Customer c = new Customer();
		c.setUname(username);
		c.setBirth(birthday);
		c.setSalary(sal);
		c.setSex(se);
		
		CustomerServiceFactory factory =null;
		try {
			factory = (CustomerServiceFactory) ServiceFactory.getServiceFactory(CustomerServiceFactory.CUSTOMER);
		} catch (MyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    CustomerService cSer = factory.getService();
	    if(cSer.addCustomer(c,favcIds)){
	    	response.sendRedirect("list");
	    }else{
	    	request.getRequestDispatcher("error").forward(request, response);
	    }
	    
	    
	}

}
